(function() {
    "use strict";

    /**
     * @ngdoc function
     * @name webApp.controller:StoredistributionCtrl
     * @description
     * # StoredistributionCtrl
     * Controller of the webApp
     */
    angular.module("webApp").controller("StoredistributionCtrl", StoredistributionCtrl);

    StoredistributionCtrl.$inject = [
        "$scope",
        "$rootScope",
        "$state",
        "dataService",
        "$location",
        "helper",
        "$timeout",
        "sessionService",
        "cacheService",
        "ERP_CONFIG",
        "$compile",
        "moment",
        "base64"
    ];


    function StoredistributionCtrl(
        $scope,
        $rootScope,
        $state,
        dataService,
        $location,
        helper,
        $timeout,
        sessionService,
        cacheService,
        ERP_CONFIG,
        $compile,
        moment,
        base64
    ) {
        $scope.listAction = function() {
            $scope.getstoreList();
        };
        //
        $scope.grouplistAction = function() {
            $scope.getgroupList();
        }

        //查询分组
        $scope.getgroupList = function(pageNo) {
            var query = {
                page_no: pageNo ? pageNo : 1,
                page_size: $scope.page_size ? $scope.page_size : 10,
            };

            dataService.getStoredistributionGroup(query).then(function(list) {
                if (list && list.total_count) {
                    $scope.groupList = list.fz_list;
                    $scope.groupTotal = list.total_count;
                }
            });
        }

        $scope.groupaddAction = function() {
            $scope.fz_group_id = $location.search().fz_group_id;
            if ($scope.fz_group_id) {
                var query = {
                    fz_group_id: $scope.fz_group_id
                };
                dataService.getStoredistributionGroup(query).then(function(list) {
                    if (list && list.total_count) {
                        $scope.group = list.fz_list[0];
                        console.error("store", $scope.group);
                    }
                });
            }
        }

        $scope.groupAdd = function() {
            // 分组类型
            $scope.group.type = 2;

            dataService.getStoredistributionAdd($scope.group).then(function(a) {
                if (a.Msg) {
                    helper.myAlert(a.Msg);
                } else {
                    helper.myAlert("success", "#/storedistribution/grouplist");
                }
            });
        }

        $scope.loglistAction = function() {
            $scope.pageNo = 1;
            $scope.page_size1 = 10;
            $scope.chosedStatus = "1";
            $scope.chosedOrderType = "1";
            $scope.chosedOrderStatus = "S_ORDER_WAIT_CONFIRM";
            $scope.getfzlog();
        }

        //获取store列表
        $scope.getfzlog = function(pageNo) {
            $scope.pageNo = pageNo;
            var query = {
                page_no: pageNo ? pageNo : $scope.pageNo,
                page_size: $scope.page_size1 ? $scope.page_size1 : 10,
                store_id: $rootScope.store_id
            };

            if ($scope.chosedStatus == 1 || $scope.chosedStatus == 2 || $scope.chosedStatus == 4) {
                if ($scope.chosedStatus) {
                    query.type = $scope.chosedStatus;
                    if ($scope.chosedStatus == 4) {
                        query.type = 3;
                    }
                }

                if ($scope.chosedStatus == 1 && $scope.chosedOrderStatus) {
                    query.order_type = 1;
                    query.status = $scope.chosedOrderStatus;
                }

                if ($scope.chosedOrderType == 2) {
                    query.order_type = 2;
                }

                dataService.getfzlog(query).then(function(list) {
                    if (list) {
                        $scope.List = list.fz_list;
                        $scope.storeTotal = list.total_count;
                    }
                });
            }

            if ($scope.chosedStatus == 3) {
                console.error("订单表和支付订单表联表查！");
                dataService.getFreezeLog(query).then(function(list) {
                    if (list) {
                        $scope.freeze_log_list = list.freeze_log_list;
                        $scope.freeze_count = list.total_count;
                    }
                });
            }
        };

        //获取store列表
        $scope.getstoreList = function(pageNo) {
            var query = {
                page_no: pageNo ? pageNo : 1,
                page_size: $scope.page_size ? $scope.page_size : 10,
                store_id: $rootScope.store_id
            };
            if ($scope.fs_id) {
                query.fs_id = $scope.fs_id;
            }
            dataService.getStoredistribution(query).then(function(list) {
                if (list && list.total_count) {
                    $scope.storeList = list.fz_list;
                    $scope.storeTotal = list.total_count;
                    if ($scope.fs_id) {
                        $scope.store = list.fz_list[0];
                        $scope.store.z1 = $scope.store.z1 ? JSON.parse($scope.store.z1) : $scope.store.z1;
                        $scope.store.z2 = $scope.store.z2 ? JSON.parse($scope.store.z2) : $scope.store.z2;
                        $scope.store.z3 = $scope.store.z3 ? JSON.parse($scope.store.z3) : $scope.store.z3;
                        $scope.store.z4 = $scope.store.z4 ? JSON.parse($scope.store.z4) : $scope.store.z4;
                        $scope.store.z5 = $scope.store.z5 ? JSON.parse($scope.store.z5) : $scope.store.z5;
                        $scope.store.config = $scope.store.config ? JSON.parse($scope.store.config) : $scope.store.config;
                    }
                }
            });
        };

        $scope.addAction = function(data) {
            console.error("data", data);
            $scope.store = {};
            $scope.fs_id = $location.search().fs_id;
            if ($scope.fs_id) {
                $scope.getstoreList();
            } else {
                $scope.store = {};
            }
        }

        $scope.getstoreOne = function(pageNo) {
            var query = {
                fs_id: $scope.fs_id,
            };
            return dataService.getStoredistribution(query).then(function(list) {
                if (list && list.total_count) {
                    return $scope.store = list.fz_list[0];
                }
            });
        };

        $scope.itemAction = function(data) {
            $scope.barcodes = 0;
            $scope.fz_group_id = $location.search().fz_group_id;
            console.error("$scope.fz_group_id", $scope.fz_group_id);
            if ($scope.fz_group_id) {
                $scope.getFzItemList();
            }
        }

        $scope.check = function(list, ck) {
            if (list && ck) {
                $scope.checkdata = list;
            }
        }

        $scope.getFzItemList = function(pageNo) {
            // console.error("store", $scope.store);
            var query = {};
            var key = $rootScope.store_id + $scope.fz_group_id + "StoredistributionCtrl";
            var cache = cacheService.get(key);
            if (pageNo || !cache) {
                var query = {
                    page_no: pageNo ? pageNo : 1,
                    page_size: $scope.page_size ? $scope.page_size : 10,
                    fz_group_id: $scope.fz_group_id,
                    store_id: $rootScope.store_id
                };
                if ($scope.keyword) {
                    query.title = $scope.keyword;
                }
                if ($scope.item_id) {
                    query.item_id = $scope.item_id;
                }

                cacheService.set(key, query);
            } else {
                query = clone(cache);
                $scope.queryRcache(query);
            }

            var querys = clone(query);

            dataService.getFzitems(querys).then(function(list) {
                if (list && list.total_count) {
                    $scope.items = list.list;
                    $scope.Total = list.total_count;
                    console.error("$scope.items", $scope.items);
                } else {
                    helper.myAlert(list.Msg);
                }
            });
        }

        $scope.queryRcache = function(query) {
            $scope.pageNo = query.page_no;
            $scope.page_size = query.page_size;
            if ($scope.keyword) {
                query.title = $scope.keyword;
            }
            if ($scope.item_id) {
                query.item_id = $scope.item_id;
            }
        };

        $scope.checkedNotAll = function() {
            if ($scope.barcode) {
                //循环
                var noData = [];
                var itemList = clone($scope.items);
                _.map(itemList, function(item, key) {
                    for (var i = 0; i < $scope.barcode.length; i++) {
                        for (var j = 0; j < item.sku.length; j++) {
                            if (item.sku[j]) {
                                if ($scope.barcode[i].barcode === item.sku[j].barcode) {
                                    item.sku.splice(j, 1);
                                }
                            }
                        }
                    }
                })
                $scope.checkedAll(itemList);
            }
        }

        //搜索 商品
        $scope.search = function() {
            $scope.getFzItemList();
        }
        $scope.checkedAll = function(items) {
            $timeout(function() {
                $scope.barcode = [];
                items = items ? items : $scope.items;
                _.map(items, function(item, key) {
                    _.map(item.sku, function(data, key) {
                        console.error("noData", data);
                        if (data) {
                            $scope.barcode.push(data);
                        }
                    })
                })
                $scope.checkdata = $scope.barcode[$scope.barcode.length - 1];
            });
        }

        $scope.saveOneData = function(data) {
            if ($scope.auditData([data])) {
                helper.myAlert("百分比之和不能大于等于100%");;
                return;
            }
            if (!data.money_type) {
                helper.myAlert("没有设置分账类型！");
                return false;
            }
            dataService.addItemsdistribution(data).then(function(a) {
                if (!a.Msg) {
                    helper.myAlert("success", null, null, function() {
                        $scope.getFzItemList();
                    });
                } else {
                    helper.myAlert(a.Msg);
                }
            });
        }

        //批量保存数据
        $scope.saveData = function() {
            if ($scope.auditData([$scope.checkdata])) {
                helper.myAlert("百分比之和不能大于等于100%");
                return;
            }

            if ($scope.barcode.length) {
                async.map($scope.barcode, function(data, callback) {
                    data.r1 = $scope.checkdata.r1;
                    data.r2 = $scope.checkdata.r2;
                    data.r3 = $scope.checkdata.r3;
                    data.r4 = $scope.checkdata.r4;
                    data.r5 = $scope.checkdata.r5;
                    dataService.addItemsdistribution(data).then(function(a) {
                        if (a.Msg) {
                            callback(null, null);
                        } else {
                            callback(null, null);
                        }
                    });
                }, function(e, r) {
                    helper.myAlert("success", null, null, function() {
                        $scope.getFzItemList();
                    });
                });
            }
        }

        $scope.auditData = function(barcode) {
            // console.error("sumValue",barcode,barcode.length);
            if (barcode.length == 1) {
                var sumValue = parseFloat(barcode[0].r1) + parseFloat(barcode[0].r2) + parseFloat(barcode[0].r3) + parseFloat(barcode[0].r4) + parseFloat(barcode[0].r5);
                // console.error("sumValue========",sumValue);
                if (sumValue < 100) {
                    return false;
                }

                if (sumValue >= 100) {
                    return true;
                }
            }
        }

        $scope.storeAdd = function() {
            //addStoredistribution
            var data = clone($scope.store);
            data.z1 = JSON.stringify(data.z1);
            data.z2 = JSON.stringify(data.z2);
            data.z3 = JSON.stringify(data.z3);
            data.z4 = JSON.stringify(data.z4);
            data.z5 = JSON.stringify(data.z5);
            data.config = JSON.stringify(data.config);
            console.error("store", data);
            dataService.addStoredistribution(data).then(function(a) {
                if (a.Msg) {
                    helper.myAlert(a.Msg);
                } else {
                    helper.myAlert("success", "#/storedistribution/list");
                }
            });
        }

        //执行分账
        $scope.implement = function(fz_log_id, order_id) {
            dataService.implementfz({
                fz_log_id: fz_log_id
            }).then(function(a) {
                if (a.Msg) {
                    helper.message("分账失败，原因：" + a.Msg, "error");
                } else {
                    helper.message("分账成功！");
                }
                $scope.getfzlog1(order_id).then(function(list) {
                    _.map($scope.List, function(da, kk) {
                        if (kk == order_id) {
                            $scope.List[kk] = list[order_id];
                        }
                    });
                });
            });
        }

        //执行分账
        $scope.NewPaySeparate = function(fz_log_id) {
            dataService.NewPaySeparate({
                fz_log_id: fz_log_id
            }).then(function(a) {
                if(a.type)
                {
                    helper.message("结算失败，原因：" + a.Msg, "error");
                }
                else
                {
                    helper.message("结算成功！");
                }
            });
        }

        $scope.getfzlog1 = function(order_id) {
            var query = {
                store_id: $rootScope.store_id,
                order_id: order_id
            };

            if ($scope.chosedStatus) {
                query.type = $scope.chosedStatus;
            }

            if ($scope.chosedStatus == 1 && $scope.chosedOrderStatus) {
                query.status = $scope.chosedOrderStatus;
            }

            return dataService.getfzlog(query).then(function(list) {
                if (list) {
                    return list.fz_list;
                }
            });
        };

        //查询分账状态  //备用金查询 getByj
        $scope.getFz = function(fz_log_id, type) {
            dataService.getfz({
                fz_log_id: fz_log_id,
                type: type
            }).then(function(a) {
                if (a.Msg) {
                    helper.myAlert(a.Msg);
                } else {
                    helper.myAlert("success");
                }
            });
        }

        //完结分账
        $scope.fzFinish = function(order_id) {
            helper.myConfirm("确定分账已经完成，需要完结么？", function() {
                dataService.fzFinish({
                    order_id: order_id
                }).then(function(a) {
                    if (a.Msg == "ok") {
                        helper.message("分账已完结！");
                    } else {
                        helper.message("error：" + a.Msg, "error");
                    }
                    $scope.getfzlog1(order_id).then(function(list) {
                        _.map($scope.List, function(da, kk) {
                            if (kk == order_id) {
                                $scope.List[kk] = list[order_id];
                            }
                        });
                    });
                });
            });
        }
    }
})();